import React from "react";
import Layout from "@/layouts";
import Lazyload from "@/components/Lazyload";
import Loading from "@/components/Loading";
import RouterGuard from "./RouterGuard";
import type { RouteObjectType } from "@/typings/router";
import { staticRenderRoutes } from "@/routers/helper/StaticRenderRouter";
import { Navigate } from "react-router";

const modules: Record<string, () => Promise<any>> = import.meta.glob("@/views/**/**.tsx");

/**
 * @description {Function} 根据后端返回的权限路由数据 递归处理成键值对路由数据提供给面包屑导航渲染
 * @param {RouteObjectType[]} menuList 后端返回的权限路由数据
 * @param {RouteObjectType[]} parent 父级路由数据
 * @param {Record<string, RouteObjectType[]>} result 递归结果
 */
export const getAllBreadcrumbList = (menuList: RouteObjectType[], parent: RouteObjectType[] = [], result: Record<string, RouteObjectType[]> = {}) => {
  for (const item of menuList) {
    result[item.meta!.key!] = [...parent, item];
    if (item.children) getAllBreadcrumbList(item.children, result[item.meta!.key!], result);
  }
  return result;
};

/**
 * @description {Function} 根据后端返回的权限路由数据 递归过滤掉状态不可见的路由数据提供给侧栏菜单渲染
 * @param {RouteObjectType[]} menuList 后端返回的权限路由数据
 */
export const getSidebarMenuList = (menuList: RouteObjectType[]) => {
  const cloneMenuList: RouteObjectType[] = structuredClone(menuList);

  return cloneMenuList.filter((item: RouteObjectType) => {
    item.children?.length && (item.children = getSidebarMenuList(item.children));
    return !item.meta?.isHide;
  });
};

/**
 * @description {Function} 根据后端返回的权限路由数据 children 内的子路由统一递归扁平化为一维数组路由数据
 * @param {RouteObjectType[]} menuList 后端返回的权限路由数据
 */
export const getFlatMenuList = (menuList: RouteObjectType[]): RouteObjectType[] => {
  const cloneMenuList: RouteObjectType[] = structuredClone(menuList);
  return cloneMenuList.flatMap((item: RouteObjectType) => [item, ...(item.children ? getFlatMenuList(item.children) : [])]);
};

/**
 * @description {Function} 根据后端返回的权限路由数据 处理生成为 React Router 路由数据格式
 * @param {RouteObjectType[]} menuList 后端返回的权限路由数据
 */
export const generateRouter = (menuList: RouteObjectType[]) => {
  const cloneFlatMenuList = structuredClone(getFlatMenuList(menuList));

  const renderRoutes = cloneFlatMenuList.map((r: RouteObjectType) => {
    r.children && delete r.children;
    return {
      path: r.path,
      loader: () => ({ ...r.meta, redirect: !!r.redirect }),
      hydrateFallbackElement: <Loading />,
      ...(r.meta && { meta: r.meta }),
      ...(r.redirect && { element: <Navigate to={r.redirect} /> }),
      ...(r.element && {
        element: (
          <RouterGuard>
            <Lazyload>{React.lazy(modules[`/src/views${r.element}.tsx`])}</Lazyload>
          </RouterGuard>
        )
      })
    };
  });

  // 过滤出全屏和非全屏路由
  const renderFullRoutes = renderRoutes.flatMap((item: RouteObjectType) => (item.meta?.isFull ? [item] : []));
  const renderNotFullRoutes = renderRoutes.flatMap((item: RouteObjectType) => (item.meta?.isFull ? [] : [item]));

  // 动态路由合并
  const convertRenderRoutes = [...staticRenderRoutes, ...renderFullRoutes, { element: <Layout />, children: [...renderNotFullRoutes] }];

  return convertRenderRoutes.flatMap((item: RouteObjectType) =>
    item.path === "*"
      ? [
          {
            ...item,
            element: (
              <RouterGuard>
                <Lazyload>{React.lazy(() => import("@/components/NotFound"))}</Lazyload>
              </RouterGuard>
            )
          }
        ]
      : [item]
  );
};
